package com.uenpay.im.panel.emoji;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.qyx.android.weight.edittext.Emoji;
import com.uenpay.im.R;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 * 
 */
public class EmojiAdapter extends PagerAdapter {
	private static final int ONE_PAGE_COUNT = 21;
	private LayoutInflater _inflater;
	private Context _context;
	private OnEmojiSelected _onEmojiSelected;

	public EmojiAdapter(Context context, OnEmojiSelected onEmojiSelected) {
		_context = context;
		_inflater = LayoutInflater.from(context);
		_onEmojiSelected = onEmojiSelected;
	}

	@Override
	public int getCount() {
		return (new Emoji().size() - 1 + ONE_PAGE_COUNT) / ONE_PAGE_COUNT;
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		Emoji mEmoji = new Emoji();
		int emoji_size = mEmoji.size();
		ViewPager pViewPager = ((ViewPager) container);
		int maxIndex = Math.min(ONE_PAGE_COUNT * (position + 1), emoji_size);
		Emoji[] grid = new Emoji[maxIndex - (ONE_PAGE_COUNT * position)];
		if (emoji_size > position * ONE_PAGE_COUNT) {
			int index = 0;
			for (int i = ONE_PAGE_COUNT * position; i < maxIndex; i++) {
				grid[index] = mEmoji.getEmoji(i);
				index++;
			}
		}

		View view = _inflater.inflate(R.layout.emoji_grid, container,false);
		GridView gridView = (GridView) view.findViewById(R.id.emoji_grid);
		gridView.setAdapter(new EmojiGridAdapter(_context, grid));
		pViewPager.addView(view);
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {
				EmojiGridAdapter adapter = (EmojiGridAdapter) adapterView
						.getAdapter();
				if (i == adapter.getCount() - 1) {
					_onEmojiSelected.onEmojiDeleted(adapter.getItem(i));
				} else {
					_onEmojiSelected.onEmojiSelected(adapter.getItem(i));
				}
			}
		});
		return view;
	}

	@Override
	public void destroyItem(ViewGroup collection, int position, Object view) {
		((ViewPager) collection).removeView((View) view);
	}
}
